<?php
class ModelUserUser extends Model {
	public function getTotalUsers($username) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM user WHERE username = '".$this->db->escape($username) . "'");
		return $query->row['total'];
	}
	public function getTotalUsersByEmail($email) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM user WHERE email = '".$this->db->escape(utf8_strtolower($email))."'");
		return $query->row['total'];
	}
	public function addUser($data) {
		$this->db->query("INSERT INTO user SET user_group_id = '1', firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', salt = '" . $this->db->escape($salt = token(9)) . "', username ='" . $this->db->escape($data['username']) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', status = '" . (int)$data['status'] . "', date_added = NOW()");

		$customer_id = $this->db->getLastId();
		

		//发送激活邮件开始
				$url = $this->url->link('common/login', '', true);
				$url .= "&userid=".$customer_id;
				$this->load->library("email");
				$smtpemailto = $this->db->escape($data['email']);//发送给谁
				$mailtitle = "激活邮件请勿回复";//邮件主题
				$mailcontent = "请<a href='".$url."'>点击链接</a>以激活您的账号！";//邮件内容

				$smtp = new email($smtpemailto,$mailtitle,$mailcontent);
				$state = $smtp->sendemail();
		return $customer_id;
	}	
	public function activeUser($userid) {
		$this->db->query("UPDATE user SET status = '1' WHERE user_id = '" . (int)$userid . "'");
	}
	public function getUseridByEmail($email) {
		$query = $this->db->query("SELECT DISTINCT * FROM user WHERE LCASE(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row;
	}
	public function getUseridByUsername($username) {
		$query = $this->db->query("SELECT DISTINCT * FROM user WHERE username = '" . $this->db->escape($username) . "'");

		return $query->row;
	}
	public function resetPassword($userid,$password) {
		$data = $this->db->query("SELECT salt FROM user WHERE user_id = '" . (int)$userid . "'");
		$salt = $data->row["salt"];
		$this->db->query("UPDATE user SET password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($password)))) . "' WHERE user_id = '" . (int)$userid . "'");
		return $userid;
	}
	public function getNicknameByUserid($userid) {
		$query = $this->db->query("SELECT nickname FROM user WHERE user_id = '" . $this->db->escape($userid) ."'");
		return $query->row['nickname'];
	}
	public function editNickname($nickname,$userid) {
		return $this->db->query("UPDATE user SET nickname = '".$this->db->escape($nickname)."' WHERE user_id = " . (int)$userid);
	}
}